package com.igd.account.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.igd.account.dao.AccountDao;
import com.igd.account.dao.dto.AccountEntity;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
@AllArgsConstructor
public class AccountService {

	private final AccountDao accountDao;
    
    @Transactional(rollbackFor = Exception.class)
    public void debit(Integer id, Long amount) {
        log.info("准备扣除用户id:[{}][{}]分钱.", id, amount);
        
        LambdaUpdateWrapper<AccountEntity> wrapper = Wrappers.lambdaUpdate(AccountEntity.class)
                .eq(AccountEntity::getId, id)
                .gt(AccountEntity::getBalance, 0)
                .setSql("balance = balance -" + amount);
        
        int result = accountDao.update(null, wrapper);
        
        if (result <= 0) {
            throw new RuntimeException("余额不足");
        }
    }
}
